import {
  Injectable,
  ExecutionContext,
  UnauthorizedException,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Reflector } from '@nestjs/core';
import { ConfigService } from '@nestjs/config';
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';

/**
 * JWT认证守卫
 * 默认所有接口需要登录，使用@Public()装饰器可标记为公开接口
 */
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor(
    private reflector: Reflector,
    private configService: ConfigService,
  ) {
    super();
  }

  canActivate(context: ExecutionContext) {
    // 检查是否为公开接口
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    
    if (isPublic) {
      return true;
    }

    // 检查是否使用测试 token
    const request = context.switchToHttp().getRequest();
    const authorization = request.headers.authorization;
    
    const testToken = this.configService.get<string>('TEST_TOKEN');
    if (testToken && authorization === `Bearer ${testToken}`) {
      // 创建一个测试用户对象
      request.user = {
        id: 999,
        username: 'test1',
        email: 'test1@test.com',
        nickname: 'Test User',
        avatar: null,
        isActive: true,
        createdAt: new Date(),
        updatedAt: new Date()
      };
      return true;
    }
    
    return super.canActivate(context);
  }

  handleRequest(err: any, user: any, info: any) {
    // 如果没有用户信息或有错误，抛出未授权异常
    if (err || !user) {
      throw err || new UnauthorizedException('未授权访问');
    }
    return user;
  }
}